package simulaco.dao;

import gminet.infra.dao.DataAccessObject;
import gminet.infra.db.TransactionException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import simulaco.dto.Materia;
import simulaco.dto.Situacao;

public class MateriaDAO extends DataAccessObject {

    public static Materia findByPK(int materiaId, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_MATERIA    CD_MATERIA  ");
        sbSql.append("     , A.TX_NOME       TX_NOME     ");
        sbSql.append("     , A.ID_SITUACAO   ID_SITUACAO ");
        sbSql.append("     , A.TS_CADASTRO   TS_CADASTRO ");
        sbSql.append("  FROM MATERIA        A ");
        sbSql.append(" WHERE A.CD_MATERIA = ? ");

        Materia materia = null;
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, materiaId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                materia = fromResultSet(rs);
            }
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("MateriaDAO.findByPK (" + sqle.getMessage() + ")");
        }
        return materia;
    }

    public static List<Materia> findAll(Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_MATERIA    CD_MATERIA  ");
        sbSql.append("     , A.TX_NOME       TX_NOME     ");
        sbSql.append("     , A.ID_SITUACAO   ID_SITUACAO ");
        sbSql.append("     , A.TS_CADASTRO   TS_CADASTRO ");
        sbSql.append("  FROM MATERIA  A   ");
        sbSql.append(" ORDER BY A.TX_NOME ");
        List<Materia> materiasList = new ArrayList<Materia>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Materia materia = fromResultSet(rs);
                materiasList.add(materia);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("MateriaDAO.findAll (" + sqle.getMessage() + ")");
        }
        return materiasList;
    }

    public static List<Materia> findByFilter(MateriaFilter filter, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_MATERIA    CD_MATERIA  ");
        sbSql.append("     , A.TX_NOME       TX_NOME     ");
        sbSql.append("     , A.ID_SITUACAO   ID_SITUACAO ");
        sbSql.append("     , A.TS_CADASTRO   TS_CADASTRO ");
        sbSql.append("  FROM MATERIA  A ");
        if (filter.hasCodigoConcurso()) {
            sbSql.append("     , CONCURSO_MATERIA  B ");
            sbSql.append(" WHERE A.CD_MATERIA  = B.CD_MATERIA ");
            sbSql.append("   AND B.CD_CONCURSO = ? ");
        } else {
            sbSql.append(" WHERE 1 = 1 ");
        }
        if (filter.hasPrimeiroDigito()) {
            String strLetra = filter.getPrimeiroDigito().toLowerCase();
            if (strLetra.equalsIgnoreCase("0")) {
                sbSql.append(" AND LEFT(A.TX_NOME, 1) < 'A'");
            } else {
                sbSql.append(" AND LOWER(A.TX_NOME) like '" + strLetra + "%' ");
            }
        }
        if (filter.hasNome()) {
            String strName = filter.getNome().toLowerCase();
            sbSql.append(" AND LOWER(A.TX_NOME) like '%" + strName + "%' ");
        }
        if (filter.hasCodigoSituacao()) {
            sbSql.append(" AND A.ID_SITUACAO = ? ");
        }
        sbSql.append(" ORDER BY A.TX_NOME   ");
        List<Materia> materiaList = new ArrayList<Materia>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            if (filter.hasCodigoConcurso()) {
                setInt(ps, pos++, filter.getCodigoConcurso());
            }
            if (filter.hasCodigoSituacao()) {
                setInt(ps, pos++, filter.getCodigoSituacao());
            }
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Materia materia = fromResultSet(rs);
                materiaList.add(materia);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.findByFilter (" + sqle.getMessage() + ")");
        }
        return materiaList;
    }

    public static void insert(Materia materia, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("INSERT INTO MATERIA ");
        sbSql.append("     ( CD_MATERIA   ");
        sbSql.append("     , TX_NOME      ");
        sbSql.append("     , ID_SITUACAO  ");
        sbSql.append("     , TS_CADASTRO  ");
        sbSql.append(") VALUES (?,?,?,?)  ");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setInt(ps, pos++, materia.getCodigo());
            setString(ps, pos++, materia.getNome());
            setInt(ps, pos++, materia.getSituacao().getCodigo());
            setTimestamp(ps, pos++, materia.getDataCadastro());
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("MateriaDAO.insert (" + sqle.getMessage() + ")");
        }
    }

    public static void update(Materia materia, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("UPDATE MATERIA         ");
        sbSql.append("   SET TX_NOME     = ? ");
        sbSql.append("     , ID_SITUACAO = ? ");
        sbSql.append(" WHERE CD_MATERIA  = ? ");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setString(ps, pos++, materia.getNome());
            setInt(ps, pos++, materia.getSituacao().getCodigo());
            setInt(ps, pos++, materia.getCodigo());
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("MateriaDAO.update (" + sqle.getMessage() + ")");
        }
    }

    public static void delete(Materia materia, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("DELETE FROM MATERIA  ");
        sbSql.append(" WHERE CD_MATERIA = ?");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, materia.getCodigo());
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("MateriaDAO.delete (" + sqle.getMessage() + ")");
        }
    }

    public static int getNextCodigo(Connection conn, int iRange, int eRange) throws TransactionException {

        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT MAX(CD_MATERIA) AS CD_MAX ");
            sbSql.append("  FROM MATERIA        ");
            sbSql.append(" WHERE CD_MATERIA > ? ");
            sbSql.append("   AND CD_MATERIA < ? ");
            //
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, iRange);
            setInt(ps, 2, eRange);
            ResultSet rs = ps.executeQuery();
            int max = 0;
            if (rs.next()) {
                max = rs.getInt("CD_MAX");
            }
            close(rs);
            return (max != 0 ? max : iRange) + 1;
        } catch (SQLException sqlEx) {
            throw new TransactionException(sqlEx);
        }
    }

    private static Materia fromResultSet(ResultSet rs) throws SQLException {

        // MATERIA
        Materia materia = new Materia();
        materia.setCodigo(getInt(rs, "CD_MATERIA"));
        materia.setNome(getString(rs, "TX_NOME"));
        materia.setSituacao(Situacao.getSituacaoById(getByte(rs, "ID_SITUACAO")));
        materia.setDataCadastro(getDateFromTimestamp(rs, "TS_CADASTRO"));
        //
        return materia;
    }

}
